import com.lean.android.plugin.convention.libs
import com.tencent.vasdolly.plugin.extension.ChannelConfigExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.buildscript
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import java.io.File
import java.util.regex.Pattern

class VasdollyConventionPlugin : Plugin<Project> {

    override fun apply(target: Project) {

        with(target) {
            apply(plugin = "com.tencent.vasdolly")

            configure<ChannelConfigExtension> {
                channelFile = File(projectDir, "channel")
                outputDir = File(rootDir, "apk")
                val realFlavorName = getCurrentFlavor()

                apkNameFormat = "\${versionName}-\${flavorName}-$realFlavorName-\${buildType}"

                buildTimeDateFormat = "yyyyMMdd-HH:mm:ss"
                lowMemory = false
            }
        }
    }

    private fun Project.getCurrentFlavor(): String {
        val taskRequests = gradle.startParameter.taskRequests.toString()
        val pattern: Pattern = if (taskRequests.contains("assemble")) {
            Pattern.compile("assemble(\\w+)(Release|Debug)")
        } else if (taskRequests.contains("channel")) {
            Pattern.compile("channel(\\w+)(Release|Debug)")
        } else {
            Pattern.compile("generate(\\w+)(Release|Debug)")
        }

        val matcher = pattern.matcher(taskRequests)
        return if (matcher.find()) {
            matcher.group(1)
        } else {
            ""
        }
    }
}